<template>
  <div class="twitter-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader />
    
    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu />
      
      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-title">{{ t('twitter.title') }}</div>
          <!-- 搜索输入区 -->
          <div class="search-box-container">
                <el-input
              v-model="state.queryParams.name"
              :placeholder="t('twitter.search.placeholder')"
                  clearable
                  class="search-input"
                  @clear="resetNameSearch"
                  prefix-icon="el-icon-search"
                >
                </el-input>
          </div>
        </div>
        
        <!-- 主内容区域 - 左侧筛选器 + 右侧卡片列表 -->
        <div class="twitter-main">
          <!-- 左侧筛选器，添加固定效果 -->
          <div class="filter-sidebar-container">
            <div class="filter-sidebar">
              <!-- 添加重置按钮 -->
              <div class="reset-filter-container">
                <el-button @click="resetAllFilters(true)" class="reset-filter-btn">
                  {{ t('twitter.reset.filters') }}
                </el-button>
              </div>
              
              <!-- 邮箱筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.email }">
                <div class="filter-header" @click="toggleFilter('email')">
                  <span>{{ t('twitter.email.filter') }}</span>
                  <i :class="['el-icon', state.expanded.email ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.email" class="filter-content">
                  <el-input
                    v-model="state.queryParams.email"
                    :placeholder="t('twitter.email.placeholder')"
                    clearable
                    @input="debouncedGetList"
                    class="full-width"
                  />
                </div>
              </div>
              
              <!-- 注册年份筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.createdAt }">
                <div class="filter-header" @click="toggleFilter('createdAt')">
                  <span>{{ t('twitter.registration.year') }}</span>
                  <i :class="['el-icon', state.expanded.createdAt ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.createdAt" class="filter-content">
                  <el-select
                    v-model="state.queryParams.createdAtYear"
                    multiple
                    :placeholder="t('twitter.select.year')"
                    class="year-select full-width"
                  >
                    <el-option
                      v-for="year in yearOptions"
                      :key="year"
                      :label="year"
                      :value="year"
                    />
                  </el-select>
                </div>
              </div>
              
              <!-- 关注者数量范围 -->
              <div class="filter-group" :class="{ expanded: state.expanded.followers }">
                <div class="filter-header" @click="toggleFilter('followers')">
                  <span>{{ t('twitter.followers.count') }}</span>
                  <i :class="['el-icon', state.expanded.followers ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.followers" class="filter-content">
                  <div class="followers-range-input">
                    <el-input-number 
                      v-model="state.queryParams.followersRange[0]" 
                      :min="0" 
                      :max="state.queryParams.followersRange[1]" 
                      :placeholder="t('twitter.min.value')" 
                      size="small"
                      @change="debouncedGetList"
                    />
                    <span class="range-separator">{{ t('twitter.to') }}</span>
                    <el-input-number 
                      v-model="state.queryParams.followersRange[1]" 
                      :min="state.queryParams.followersRange[0]" 
                      :placeholder="t('twitter.max.value')" 
                      size="small"
                      @change="debouncedGetList"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        
          <!-- 右侧数据内容 -->
          <div class="data-content">
            <!-- 操作按钮 -->
            <div class="export-module">
              <!-- 添加符合条件的数量显示 -->
              <div class="matched-count">
                <span>{{ t('twitter.matched.count') }}</span>
                <span class="matched-count-number" v-loading="countLoading">{{ displayedCount }}</span>
                <span>{{ t('twitter.matched.count.unit') }}</span>
              </div>
              <el-button 
                @click="handleExport" 
                class="export-module-btn"
                :loading="exportLoading"
                :disabled="exportLoading"
                type="primary"
              >
                <el-icon><Download /></el-icon>
                <span>{{ exportLoading ? t('twitter.export.loading') : t('twitter.export.data') }}</span>
              </el-button>
            </div>
            
            <!-- 卡片式联系人列表 -->
            <div v-loading="state.loading" class="contact-card-list">
              <!-- 无数据提示 -->
              <div v-if="!state.loading && state.contactsList.length === 0" class="no-data">
                <i class="el-icon-warning-outline"></i>
                <p>{{ t('twitter.no.data') }}</p>
                <div>
                  <el-button @click="resetAllFilters(true)" type="primary" size="small" class="mt-3 mr-2">
                    {{ t('twitter.reset.filters') }}
                  </el-button>
                  <el-button @click="fetchContacts" type="info" size="small" class="mt-3">
                    {{ t('twitter.reload') }}
                  </el-button>
                </div>
              </div>
              
              <!-- 骨架屏 -->
              <div v-if="state.loading && state.contactsList.length === 0" class="skeleton-loading">
                <div v-for="i in 6" :key="i" class="skeleton-card">
                  <div class="skeleton-header">
                    <div class="skeleton-avatar"></div>
                    <div class="skeleton-title"></div>
                  </div>
                  <div class="skeleton-content">
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                  </div>
                </div>
              </div>
              
              <!-- 联系人卡片 -->
              <div 
                v-for="contact in state.contactsList" 
                :key="contact.twitterId" 
                class="contact-card"
              >
                <!-- 卡片头部 -->
                <div class="card-header">
                  <div class="company-info">
                    <div class="company-avatar">
                      <el-avatar 
                        :size="50"
                        :src="getRandomAvatar(contact.twitterId, contact.name)" 
                        class="contact-avatar"
                        @error="handleAvatarError"
                      >
                        {{ contact.name ? contact.name.charAt(0).toUpperCase() : 'U' }}
                      </el-avatar>
                    </div>
                    <div class="company-name">{{ contact.name || t('twitter.unknown.user') }}</div>
                  </div>
                  <div class="detail-button-container">
                    <el-button 
                      class="detail-btn" 
                      type="primary"
                      plain
                      @click="toggleContactDetails(contact)"
                    >
                      {{ contact.expanded ? t('twitter.detail.collapse') : t('twitter.detail.expand') }}
                    </el-button>
                  </div>
                </div>
                
                <!-- 分隔线 -->
                <div class="card-divider"></div>
                
                <!-- 卡片内容 - 信息与按钮并排 -->
                <div class="info-button-container">
                  <!-- 基本信息区域 -->
                  <div class="card-basic-info">
                    <div class="basic-info-grid">
                      <div class="info-row" v-if="contact.email">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('twitter.email') }}</span>
                          <span class="info-value">
                            <el-tooltip
                              v-if="contact.email && contact.email.includes('*')"
                              :content="t('twitter.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span
                                class="masked-info"
                                @click="showFullContactInfo(contact, 'email')">
                                {{ contact.email }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ contact.email }}</span>
                          </span>
                        </div>
                      </div>
                      
                      <div class="info-row" v-if="contact.screenName">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('twitter.username') }}</span>
                          <span class="info-value">{{ contact.screenName }}</span>
                        </div>
                      </div>
                      
                      <div class="info-row" v-if="contact.followers !== undefined">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('twitter.followers') }}</span>
                          <span class="info-value">{{ contact.followers }}</span>
                        </div>
                      </div>
                      
                      <div class="info-row" v-if="contact.createdAt">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('twitter.created.time') }}</span>
                          <span class="info-value">{{ contact.createdAtFormatted }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 详细内容 - 点击详情后显示 -->
                <div class="card-content" v-if="contact.expanded">
                  <div class="detail-title">{{ t('twitter.detail.title') }}</div>
                  <!-- 参展商详细信息 -->
                  <div class="info-table-wrapper">
                    <table class="info-table">
                      <tbody>
                        <tr v-if="contact.screenName">
                          <td class="label-cell">{{ t('twitter.screenname') }}</td>
                          <td class="value-cell">{{ contact.screenName }}</td>
                        </tr>
                        <tr v-if="contact.url">
                          <td class="label-cell">{{ t('twitter.website') }}</td>
                          <td class="value-cell">
                            <a :href="contact.url" target="_blank">{{ contact.url }}</a>
                          </td>
                        </tr>
                        <tr v-if="contact.description">
                          <td class="label-cell">{{ t('twitter.description') }}</td>
                          <td class="value-cell">{{ contact.description }}</td>
                        </tr>
                        <!-- 好友数量显示 - 已注释掉 -->
                        <!-- <tr v-if="contact.friendsCount !== undefined">
                          <td class="label-cell">{{ t('twitter.friends') }}</td>
                          <td class="value-cell">{{ contact.friendsCount }}</td>
                        </tr> -->
                        <!-- 列表数量显示 - 已注释掉 -->
                        <!-- <tr v-if="contact.listedCount !== undefined">
                          <td class="label-cell">{{ t('twitter.listed') }}</td>
                          <td class="value-cell">{{ contact.listedCount }}</td>
                        </tr> -->
                        <!-- 推文数量显示 - 已注释掉 -->
                        <!-- <tr v-if="contact.statusesCount !== undefined">
                          <td class="label-cell">{{ t('twitter.statuses') }}</td>
                          <td class="value-cell">{{ contact.statusesCount }}</td>
                        </tr> -->
                        <tr v-if="contact.lastStatusSource">
                          <td class="label-cell">{{ t('twitter.last.source') }}</td>
                          <td class="value-cell">{{ contact.lastStatusSource }}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="state.queryParams.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="state.queryParams.pageSize"
                layout="sizes, prev, pager, next, jumper"
                :total="Math.max(state.total, 1)"
                background
                :prev-text="t('pagination.prev')"
                :next-text="t('pagination.next')"
                :popper-class="'custom-pagination-dropdown'"
                :pager-count="7"
                :disabled="state.loading"
              >
                <!-- 移除显示总数的模板 -->
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 导出对话框 -->
  <el-dialog
    v-model="exportDialogVisible"
    :title="t('export.dialog.title')"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>{{ t('export.matching.records') }}: <span class="export-highlight">{{ totalMatchCount }}</span></p>
        <p>{{ t('export.current.balance') }}: <span class="export-highlight">{{ userBalance.exportQuotaRemaining }}</span></p>
        <p class="export-note">{{ t('export.note') }}</p>
        <p class="export-limit-notice">{{ t('export.max.limit.notice') }}</p>
      </div>
      
      <div class="export-input">
        <p>{{ t('export.enter.count') }}</p>
        <el-input-number
          v-model="exportCount"
          :min="1"
          :max="Math.max(1, Math.min(totalMatchCount, 50000, userBalance.exportQuotaRemaining || 1))"
          :step="100"
          size="large"
          controls-position="right"
        />
        
        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.exceed') }}
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.balance') }}
          </p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">{{ t('export.cancel') }}</el-button>
        <el-button 
          type="primary" 
          @click="doExport" 
          :loading="exportLoading"
          :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount"
        >
          {{ t('export.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Lock } from '@element-plus/icons-vue'
import { t, getCurrentLanguage, addTranslation } from '@/utils/i18n'
import { 
  getTwitterUsers, 
  filterTwitterUsers, 
  exportTwitterUsers,
  getTwitterCount,
  getUserBalanceInfo,
  getTwitterFullContactInfo
} from '@/api/twitter'


const router = useRouter()

const goBack = () => {
  router.push('/')
}

// 验证登录状态
const checkLogin = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请先登录后再访问此页面')
    } else {
      ElMessage.warning('Please log in first before visiting this page')
    }
    // 将当前路径保存到本地存储，以便登录后返回
    localStorage.setItem('redirectPath', router.currentRoute.value.fullPath)
    // 使用router导航到登录页面
    router.push('/login')
    return false
  }
  return true
}

// 页面状态
const state = reactive({
  queryParams: {
    name: '',
    email: '',
    createdAtYear: [],
    followersRange: [0, 10000],
    pageNum: 1,
    pageSize: 10
  },
  loading: false,
  contactsList: [],
  total: 0,
  expanded: {
    email: false,
    createdAt: false,
    followers: false
  }
})

// 添加符合条件的数量显示相关变量
const displayedCount = ref(0)
const countLoading = ref(false)

// 导出相关的状态
const exportLoading = ref(false)
const exportDialogVisible = ref(false)
const totalMatchCount = ref(0)
const exportCount = ref(0)
const userBalance = ref({
  exportQuotaRemaining: 0
})

// 导出相关的计算属性
const isExportCountExceeded = computed(() => {
  return exportCount.value > totalMatchCount.value
})

const isBalanceInsufficient = computed(() => {
  return exportCount.value > userBalance.value.exportQuotaRemaining
})

const isExportLimitExceeded = computed(() => {
  return exportCount.value > 50000
})

// 地区选项（可以从后端获取或手动维护）
const locationOptions = ref([
  '中国',
  '美国',
  '日本',
  '韩国',
  '英国',
  '德国',
  '法国',
  '加拿大',
  '澳大利亚'
])

// 年份选项（从2000年到当前年份）
const yearOptions = ref([]);
const currentYear = new Date().getFullYear();
for (let year = 2000; year <= currentYear; year++) {
  yearOptions.value.push(year);
}

// 添加筛选器样式
const styles = `
.range-values {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}
`;

// 使用防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 创建一个防抖版本的getList
const debouncedGetList = debounce(() => {
  state.queryParams.pageNum = 1;
  getList();
}, 300);

// 监听查询参数变化
watch(
  () => [
    state.queryParams.name,
    state.queryParams.email,
    state.queryParams.createdAtYear,
    state.queryParams.followersRange
  ],
  () => {
    debouncedGetList();
  },
  { deep: true }
);

// 获取联系人列表
const getList = async () => {
  try {
    state.loading = true;
    countLoading.value = true;
    
    // 准备查询参数
    const params = {
      name: state.queryParams.name,
      email: state.queryParams.email,
      created_at_year: state.queryParams.createdAtYear,
      followers_range: state.queryParams.followersRange,
      pageNum: state.queryParams.pageNum,
      pageSize: state.queryParams.pageSize
    };
    
    const response = await filterTwitterUsers(params);
    
    if (response && response.code === 200 && response.data) {
      // 处理嵌套的数据结构
      const responseData = response.data;
      if (responseData.data && Array.isArray(responseData.data)) {
        state.contactsList = responseData.data.map(contact => ({
          ...contact,
          expanded: false,
          // 格式化数据
          followersCount: contact.followers || 0,
          createdAtFormatted: formatDateTime(contact.createdAt),
          // 对邮箱进行脱敏处理
          email: maskEmail(contact.email)
        }));
        state.total = Math.max(responseData.total || 1, 1); // 确保至少为1，避免分页不显示
      } else {
        state.contactsList = [];
        state.total = 1; // 设置为1而不是0，确保分页控件显示
      }
    } else {
      const msg = (response && response.msg) || '';
      if (msg.includes('余额不足')) {
        if (state.queryParams.pageNum !== 1) {
          state.queryParams.pageNum = 1;
        }
        return;
      }
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(t('twitter.error.fetchFailed') || '获取数据失败');
      } else {
        ElMessage.error('Failed to get contact list, please try again later.')
      }
      state.contactsList = [];
      // state.total = 1; // 设置为1而不是0，确保分页控件显示
    }
    
    // 确保total至少为1，即使没有数据也显示分页控件
    if (state.total <= 0) {
      state.total = 1;
    }
    
    // 获取符合条件的数量
    fetchExportCount();
  } catch (error) {
    try {
      const errMsg = (error && (error.response?.data?.message || error.message)) || '';
      if (errMsg.includes('余额不足')) {
        if (state.queryParams.pageNum !== 1) {
          state.queryParams.pageNum = 1;
        }
        return;
      }
    } catch (_) { /* ignore */ }
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(t('twitter.error.fetchFailed') || '获取联系人列表失败');
    } else {
      ElMessage.error('Failed to get contact list, please try again later.')
    }
    state.contactsList = [];
    state.total = 0; // 设置为1而不是0，确保分页控件显示
    displayedCount.value = '0';
  } finally {
    state.loading = false;
    countLoading.value = false;
  }
};

// 重置姓名搜索
const resetNameSearch = () => {
  state.queryParams.name = '';
  getList();
};

// 重置所有筛选条件
const resetAllFilters = (isFromUserClick = false) => {
  // 重置所有筛选展开状态
  Object.keys(state.expanded).forEach(key => {
    state.expanded[key] = false;
  });
  
  // 重置查询参数
  state.queryParams = {
    name: '',
    email: '',
    createdAtYear: [],
    followersRange: [0, 10000],
    pageNum: 1,
    pageSize: 10
  };
  
  // 获取数据
  getList();
  
  // 只有在用户明确点击重置按钮时才显示成功消息
  if (isFromUserClick) {
    ElMessage.success(t('twitter.reset.filters.success') || '已重置筛选条件');
  }
};

// 获取随机头像
const getRandomAvatar = (id, name) => {
  // 使用姓名作为seed生成一致的头像
  if (name) {
    const seed = name.toLowerCase().replace(/\s/g, '');
    const styles = ['micah', 'avataaars', 'adventurer', 'bottts', 'personas'];
    const style = styles[Math.abs(seed.charCodeAt(0)) % styles.length];
    return `https://api.dicebear.com/7.x/${style}/svg?seed=${seed}`;
  }
  
  // 使用ID生成头像
  const styles = ['micah', 'avataaars', 'adventurer', 'bottts', 'personas'];
  const style = styles[Math.abs(id) % styles.length];
  return `https://api.dicebear.com/7.x/${style}/svg?seed=${id}`;
};

// 处理头像加载错误
const handleAvatarError = (e) => {
  const seed = Math.random().toString(36).substring(2, 8);
  e.target.src = `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`;
};

// 格式化性别
const formatGender = (gender) => {
  if (!gender) return '未知';
  return gender === 'Male' ? '男' : '女';
};

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '';
  const date = new Date(datetime);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 邮箱脱敏处理函数
const maskEmail = (email) => {
  if (!email) return '';
  const parts = email.split('@');
  if (parts.length !== 2) return email;
  
  const name = parts[0];
  const domain = parts[1];
  
  if (name.length <= 3) {
    return email;
  }
  
  return `${name.substring(0, 3)}***@${domain}`;
};

// 获取掩码后的电话
const getMaskedPhone = (phone) => {
  if (!phone) return '';
  const phoneStr = String(phone);
  
  if (phoneStr.length <= 3) {
    return phoneStr;
  }
  
  return `${phoneStr.substring(0, 3)}********`;
};

// 切换联系人详情展开/收起
const toggleContactDetails = (contact) => {
  contact.expanded = !contact.expanded;
};

// 处理导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 先获取符合条件的记录数量
    await fetchExportCount()
    
    // 再获取用户余额
    await fetchUserBalance()
    
    // 显示导出对话框
    exportDialogVisible.value = true
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('准备导出失败，请稍后重试')
    } else {
      ElMessage.error('Failed to prepare export, please try again later.')
    }
  } finally {
    exportLoading.value = false
  }
};

// 获取符合条件的记录数量
const fetchExportCount = async () => {
  try {
    countLoading.value = true;
    const params = {
      name: state.queryParams.name,
      email: state.queryParams.email,
      created_at_year: state.queryParams.createdAtYear,
      followers_range: state.queryParams.followersRange
    };
    const response = await getTwitterCount(params);
    
    if (response.code === 200) {
      // 从响应中提取count字段
      const count = response.data.count || 0;

      totalMatchCount.value = count > 50000 ? 50000 : count;
      exportCount.value = Math.min(totalMatchCount.value, 1000); // 默认设置为1000条或总数
      
      // 更新显示的数量
      if (count > 10000) {
        displayedCount.value = '10,000+'; // 超过10000条显示10000+
      } else {
        displayedCount.value = formatNumber(count);
      }
      
      return count;
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(response.msg || '获取记录数量失败');
      } else {
        ElMessage.error('Failed to get record count, please try again later.');
      }
      displayedCount.value = 0;
      return 0;
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取记录数量失败，请稍后重试');
    } else {
      ElMessage.error('Failed to get record count, please try again later.');
    }
    displayedCount.value = 0;
    return 0;
  } finally {
    countLoading.value = false;
  }
};

// 格式化数字的函数
const formatNumber = (num) => {
  if (num === null || num === undefined) return '0';
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 获取用户余额
const fetchUserBalance = async () => {
  try {
    const response = await getUserBalanceInfo();
    
    if (response.code === 200 && response.data) {
      userBalance.value = response.data;
      return response.data;
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(response.msg || '获取余额信息失败');
      } else {
        ElMessage.error('Failed to get balance info, please try again later.');
      }
      return { exportQuotaRemaining: 0 };
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取余额信息失败，请稍后重试');
    } else {
      ElMessage.error('Failed to get balance info, please try again later.');
    }
    return { exportQuotaRemaining: 0 };
  }
};

// 执行导出操作
const doExport = async () => {
  // 检查导出数量
  if (isExportCountExceeded.value) {
    ElMessage.error(t('twitter.export.error.exceed'));
    return;
  }
  
  // 检查导出上限
  if (isExportLimitExceeded.value) {
    ElMessage.error(t('twitter.export.error.limit'));
    return;
  }
  
  // 检查余额
  if (isBalanceInsufficient.value) {
    ElMessage.error(t('twitter.export.error.balance'));
    return;
  }
  
  // 确保导出数量是有效的数字
  if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
    ElMessage.error(t('twitter.export.error.invalid.count') || '请输入有效的导出数量');
    return;
  }
  
  exportLoading.value = true;
  try {
    // 准备导出参数对象
    const exportParams = {
      name: state.queryParams.name,
      email: state.queryParams.email,
      created_at_year: state.queryParams.createdAtYear,
      followers_range: state.queryParams.followersRange,
      exportCount: Number(exportCount.value) // 确保转换为数字类型
    };
    
    ElMessage.info(t('twitter.export.preparing') || '正在准备导出数据，请稍候...');
    
    // 发送请求
    const response = await exportTwitterUsers(exportParams);
    
    // 处理下载逻辑
    if (response && response.data instanceof Blob) {
      // 创建Blob对象
      const blob = response.data;
      
      // 获取文件名
      let fileName = 'twitter_users.xlsx';
      const disposition = response.headers && response.headers['content-disposition'];
      if (disposition && disposition.includes('filename=')) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
          fileName = matches[1].replace(/['"]/g, '');
        }
      }
      
      // 下载文件
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 关闭导出对话框
      exportDialogVisible.value = false;
      ElMessage.success(t('twitter.export.success') || '导出成功');
    } else {
      throw new Error(t('twitter.export.error.format') || '导出失败：响应格式不正确');
    }
  } catch (error) {
    ElMessage.error(t('twitter.export.error.failed') || '导出失败，请稍后重试');
  } finally {
    exportLoading.value = false;
  }
};

// 切换筛选面板显示状态
const toggleFilter = (filterName) => {
  state.expanded[filterName] = !state.expanded[filterName];
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  state.queryParams.pageSize = size;
  state.queryParams.pageNum = 1;
  getList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  state.queryParams.pageNum = page;
  getList();
};

// 页面加载时获取数据
onMounted(() => {
  // 添加翻译
  addTranslation('twitter.matched.count', {
    zh: '符合条件的联系人：',
    en: 'Matched Contacts: '
  });
  
  addTranslation('twitter.matched.count.unit', {
    zh: ' 条',
    en: ' items'
  });
  
  // 添加导出对话框标题翻译
  addTranslation('export.dialog.title', {
    zh: '导出数据',
    en: 'Export Data'
  });
  
  // 添加导出限制提示翻译
  addTranslation('export.max.limit.notice', {
    zh: '最多可导出50000条记录',
    en: 'Maximum export limit is 50,000 records'
  });
  
  // 添加导出限制错误消息翻译
  addTranslation('twitter.export.error.limit', {
    zh: '导出数量不能超过50000条',
    en: 'Export quantity cannot exceed 50,000 records'
  });
  
  // 添加导出弹窗相关翻译
  addTranslation('export.matching.records', {
    zh: '符合条件的记录数',
    en: 'Matching records'
  });
  
  addTranslation('export.current.balance', {
    zh: '当前导出余额',
    en: 'Current export balance'
  });
  
  addTranslation('export.note', {
    zh: '注意: 每导出一条记录将消耗一点导出额度',
    en: 'Note: Each exported record will consume one export credit'
  });
  
  addTranslation('export.enter.count', {
    zh: '请输入要导出的记录数:',
    en: 'Please enter the number of records to export:'
  });
  
  addTranslation('export.warning.exceed', {
    zh: '导出数量不能超过符合条件的记录数',
    en: 'Export quantity cannot exceed the number of matching records'
  });
  
  addTranslation('export.warning.balance', {
    zh: '导出余额不足',
    en: 'Insufficient export balance'
  });
  
  addTranslation('export.warning.limit', {
    zh: '导出数量不能超过50000条',
    en: 'Export quantity cannot exceed 50,000 records'
  });
  
  addTranslation('export.cancel', {
    zh: '取消',
    en: 'Cancel'
  });
  
  addTranslation('export.confirm', {
    zh: '确认导出',
    en: 'Confirm Export'
  });
  
  // 添加敏感信息处理相关的翻译键
  addTranslation('twitter.view.full.contact.tooltip', {
    zh: '点击消耗一次次数查看完整信息',
    en: 'Click to view full information (costs 1 credit)'
  });

  addTranslation('twitter.confirm.view.contact', {
    zh: '查看完整联系信息将消耗一次查看次数，是否继续？',
    en: 'Viewing full contact information will cost 1 credit. Continue?'
  });

  addTranslation('twitter.view.full.contact', {
    zh: '查看完整联系信息',
    en: 'View Full Contact Information'
  });

  addTranslation('twitter.confirm', {
    zh: '确认',
    en: 'Confirm'
  });

  addTranslation('twitter.cancel', {
    zh: '取消',
    en: 'Cancel'
  });

  addTranslation('twitter.contact.view.success', {
    zh: '联系信息获取成功',
    en: 'Contact information retrieved successfully'
  });

  addTranslation('twitter.contact.view.error', {
    zh: '获取联系信息失败，请稍后重试',
    en: 'Failed to retrieve contact information, please try again later'
  });
  
  getList();
  
  // 添加延时获取联系人数量，确保在初始化完成后更新显示的联系人数量
  setTimeout(() => {
    fetchExportCount();
  }, 800);
});

// 处理敏感信息的点击事件 - 获取完整联系信息
const showFullContactInfo = async (contact, field) => {
  // 只有当信息包含星号时才需要查询完整信息
  if (!(contact[field] && contact[field].includes('*'))) {
    return;
  }

  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      t('twitter.confirm.view.contact'),
      t('twitter.view.full.contact'),
      {
        confirmButtonText: t('twitter.confirm'),
        cancelButtonText: t('twitter.cancel'),
        type: 'warning'
      }
    );

    const response = await getTwitterFullContactInfo(contact.sourceId, contact.sourceTable, field);

    if (response.code === 200 && response.data) {
      // 更新当前联系人的信息
      if (response.data[field]) {

        // 直接更新字段值
        contact[field] = response.data[field];

        // 同时更新contactsList中对应的联系人数据
        const contactIndex = state.contactsList.findIndex(c => 
          c.sourceId === contact.sourceId && c.sourceTable === contact.sourceTable);
        if (contactIndex !== -1) {
          state.contactsList[contactIndex][field] = response.data[field];
        }

      }

      ElMessage.success(t('twitter.contact.view.success'));
    } else {
      ElMessage.error(response.msg || t('twitter.contact.view.error'));
    }
  } catch (error) {
    if (error !== 'cancel') {

      // 处理特定错误，如余额不足
      if (error.response && error.response.data && error.response.data.msg) {
        ElMessage.error(error.response.data.msg);
      } else {
        ElMessage.error(t('twitter.contact.view.error'));
      }
    }
  }
};
</script>

<style scoped>
.twitter-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background-color: #f5f7fa;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #f5f7fa;
}

/* 搜索区域样式 */
.search-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.search-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.search-box-container {
  width: 100%;
  max-width: 400px;
}

.search-input {
  width: 100%;
  font-size: 16px;
}

.search-input :deep(.el-input__inner) {
  font-size: 16px;
  height: 45px;
  text-align: center;
}

/* 主内容区布局 - 优化响应式 */
.twitter-main {
  display: flex;
  gap: 20px;
  flex: 1;
  min-width: 0; /* 防止flex子元素溢出 */
}

/* 筛选侧边栏样式 - 响应式宽度 */
.filter-sidebar-container {
  width: 280px;
  flex-shrink: 0;
  position: relative;
  min-width: 250px; /* 最小宽度保证可用性 */
}

.filter-sidebar {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

/* 重置筛选器按钮 */
.reset-filter-container {
  margin-bottom: 15px;
  text-align: center;
}

.reset-filter-btn {
  width: 100%;
}

/* 筛选组样式 */
.filter-group {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.filter-group.expanded {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.filter-content {
  padding: 15px;
  max-height: 250px;
  overflow-y: auto;
}

.full-width {
  width: 100%;
}

/* 右侧数据内容区 - 优化布局 */
.data-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0; /* 防止内容溢出 */
  max-width: 100%; /* 确保不超出容器 */
}

/* 导出模块 - 响应式优化 */
.export-module {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  flex-wrap: wrap; /* 允许按钮换行 */
  gap: 10px; /* 按钮间距 */
}

.export-module-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 添加符合条件数量样式 */
.matched-count {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
}

.matched-count-number {
  font-weight: bold;
  color: #409eff;
  margin: 0 2px;
}

/* 联系人卡片列表 - 响应式网格布局 */
.contact-card-list {
  display: grid;
  grid-template-columns: 1fr; /* 默认单列 */
  gap: 15px;
  margin-bottom: 20px;
  width: 100%;
}

/* 骨架屏 */
.skeleton-loading {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.skeleton-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 250px;
}

.skeleton-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.skeleton-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #eee;
  margin-right: 15px;
  animation: skeleton-loading 1.5s infinite;
}

.skeleton-title {
  width: 70%;
  height: 20px;
  background-color: #eee;
  animation: skeleton-loading 1.5s infinite;
}

.skeleton-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.skeleton-line {
  height: 15px;
  background-color: #eee;
  animation: skeleton-loading 1.5s infinite;
}

@keyframes skeleton-loading {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

/* 联系人卡片样式 - 优化网格布局适配 */
.contact-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box; /* 确保padding不影响宽度计算 */
  min-height: 200px; /* 保证卡片最小高度 */
}

.contact-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.company-info {
  display: flex;
  align-items: center;
}

.company-avatar {
  margin-right: 15px;
}

.contact-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.company-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.card-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 10px 0;
}

.info-button-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card-basic-info {
  flex: 1;
}

.basic-info-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item.full-width {
  flex: 1 1 100%;
}

.info-label {
  color: #909399;
  margin-right: 5px;
  font-size: 14px;
}

.info-value {
  color: #606266;
  font-size: 14px;
  word-break: break-word;
}

/* 敏感信息遮罩样式 */
.masked-info {
  cursor: pointer;
  color: #1976D2;
  text-decoration: none;
  transition: color 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.masked-info:hover {
  color: #0D47A1;
  text-decoration: underline;
}

.info-lock-icon {
  font-size: 12px;
  color: #909399;
  margin-left: 2px;
}

.masked-info:hover .info-lock-icon {
  color: #0D47A1;
}

.detail-button-container {
  margin-left: 10px;
}

.detail-btn {
  min-width: 80px;
  transition: all 0.3s;
}

/* 为收起状态添加特殊样式 */
.el-button.detail-btn:not(.is-plain) {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 详细信息区域 */
.card-content {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.info-table-wrapper {
  overflow-x: auto;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 8px 10px;
  border-bottom: 1px solid #ebeef5;
}

.label-cell {
  width: 120px;
  color: #909399;
  font-size: 14px;
  vertical-align: top;
}

.value-cell {
  color: #606266;
  font-size: 14px;
  word-break: break-word;
}

/* 分页器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 25px;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.pagination-container :deep(.el-pagination) {
  font-weight: normal;
  justify-content: center;
  width: 100%;
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.export-limit-notice {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style> 
